package com.yunyouyi.intelligent_vehicle.configuration;

import com.yunyouyi.intelligent_vehicle.util.AjaxResult;
import com.yunyouyi.intelligent_vehicle.util.MyException;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@Slf4j
@Controller
@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 所有异常捕获
     * @param req
     * @param e
     * @return
     * @throws Exception
     */
    @ExceptionHandler(value = Exception.class)
    public AjaxResult defaultErrorHandler(HttpServletRequest req, Exception e) throws Exception {
        log.error(e.getMessage(), e);
        return AjaxResult.error(e.getMessage());
    }

    /**
     * 自定义异常捕获
     * @param req
     * @param e
     * @return
     * @throws Exception
     */
    @ExceptionHandler(value = MyException.class)
    @ResponseBody
    public AjaxResult jsonErrorHandler(HttpServletRequest req, MyException e) throws Exception {
        log.error(e.getMessage(), e);
        return  AjaxResult.error(e.getMessage());
    }

    /**
     * 方法参数校验
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public AjaxResult handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        log.error("{}",e);
        return AjaxResult.error(e.getBindingResult().getFieldError().getDefaultMessage());
    }

    /*@ExceptionHandler(AuthorizationException.class)
    public ResultDto handleAuthorizationExceptionException(AuthorizationException e) {
        log.error(e.getMessage(), e);
        return new ResultDto("000001","没有操作权限","");
    }*/

}